#include "jsonparse.h"

#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>

// 声明静态变量
JsonParse JsonParse::m_json;

static QString CliKeys[] =
{
    "ServerID", "ClientID", "Host", "Port", "ShmKey"
};

static QString SerKeys[] =
{
    "ServerID", "Port", "DBHost", "DBPort",
    "DBName", "DBUserName", "DBPasswd",
    "ShmMaxNode", "ShmKey"
};

QString &CliConfig::operator [](int index)
{
    switch(index)
    {
    case 0:
       return serverID;
    case 1:
       return clientID;
    case 2:
       return ip;
    case 3:
       return port;
    case 4:
       return shmKey;
    default:
       return shmKey;
    }
}

QString &SerConfig::operator [](int index)
{
    switch(index)
    {
    case 0:
       return serverID;
    case 1:
       return port;
    case 2:
       return dbHost;
    case 3:
       return dbPort;
    case 4:
       return dbName;
    case 5:
       return dbUserName;
    case 6:
        return dbPasswd;
    case 7:
        return shmMaxNode;
    case 8:
        return shmKey;
    default:
        return shmKey;
    }
}

///////////////////////////////////////////////
///             Class JsonParse
///////////////////////////////////////////////

void JsonParse::writeClientConfig(CliConfig cfg)
{
    writeConfig(Client, &cfg);
}

CliConfig JsonParse::readClientConfig()
{
    CliConfig conf;
    readConfig(Client, &conf);
    return conf;
}

void JsonParse::writeServerConfig(SerConfig cfg)
{
    writeConfig(Server, &cfg);
}

SerConfig JsonParse::readServerConfig()
{
    SerConfig conf;
    readConfig(Server, &conf);
    return conf;
}

bool JsonParse::configIsExist(JsonParse::Type p)
{
    QFileInfo info;
    QString name = p == Type::Client ? CliFileName : SerFileName;
    bool bl = info.exists(name);
    return bl;
}

JsonParse::JsonParse()
{
}

JsonParse::JsonParse(JsonParse &)
{
}

JsonParse* JsonParse::getInstance()
{
    return &m_json;
}

bool JsonParse::makeDirectory(QString name)
{
    QDir dir;
    bool bl = dir.exists(name);
    if(!bl)
    {
        bl = dir.mkdir(name);
    }
    return bl;
}

void JsonParse::writeConfig(JsonParse::Type t, void *config)
{
    makeDirectory();
    // 写文件
    QString fileName = t==Type::Client ? CliFileName : SerFileName;
    QFile file(fileName);
    bool bl = file.open(QFile::WriteOnly);
    if(bl)
    {
        // 组织数据
        QJsonObject obj;
        if(t == Type::Client)
        {
            CliConfig *cfg = (CliConfig*)config;
            for(int i=0; i<cfg->size(); ++i)
            {
                obj.insert(CliKeys[i], (*cfg)[i]);
            }
        }
        else
        {
            SerConfig *cfg = (SerConfig*)config;
            for(int i=0; i<cfg->size(); ++i)
            {
                obj.insert(SerKeys[i], (*cfg)[i]);
            }
        }

        QJsonDocument doc(obj);
        QByteArray json = doc.toJson();
        file.write(json);
    }
    file.close();
}

void JsonParse::readConfig(JsonParse::Type t, void *config)
{
    QString fileName = t==Type::Client ? CliFileName : SerFileName;
    QFile file(fileName);
    bool flag = file.open(QFile::ReadOnly);
    if(flag)
    {
        // 文件存在
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        QJsonObject obj = doc.object();
        if(t == Client)
        {
            CliConfig *cfg = (CliConfig*)config;
            for(int i=0; i<cfg->size(); ++i)
            {
                (*cfg)[i] = obj.value(CliKeys[i]).toString();
            }
        }
        else
        {
            SerConfig *cfg = (SerConfig*)config;
            for(int i=0; i<cfg->size(); ++i)
            {
                (*cfg)[i] = obj.value(SerKeys[i]).toString();
            }
        }
    }
    file.close();
}

QByteArray JsonParse::generateSimpleObj(QStringList keys, QStringList values)
{
    QJsonObject obj;
    for(int i=0; i<keys.size(); ++i)
    {
        obj.insert(keys.at(i), values.at(i));
    }
    QJsonDocument doc(obj);
    return doc.toJson();
}

QString JsonParse::simpleObjValue(QString json, QString key)
{ 
    QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
    QJsonObject obj = doc.object();
    return obj[key].toString();
}

void JsonParse::writeLoginInfo(QString id, QString pwd, JsonParse::Type t)
{
    QByteArray array;
    QFile file(LoginFileName);
    bool fl = file.open(QFile::ReadOnly);
    if(fl)
    {
        // 打开文件成功
        QByteArray json = file.readAll();
        QJsonObject obj = QJsonDocument::fromBinaryData(json).object();
        QJsonObject subcli = obj.value("Client").toObject();
        QJsonObject subSer = obj.value("Server").toObject();

        if(t == Type::Client)
        {
            subcli["NodeID"] = id;
            subcli["Passwd"] = pwd;
        }
        else
        {
            subSer["NodeID"] = id;
            subSer["Passwd"] = pwd;
        }
        QJsonObject obj1;
        obj1.insert("Client", subcli);
        obj1.insert("Server", subSer);
        QJsonDocument doc(obj1);
        array = doc.toBinaryData();
    }
    else
    {
        // 文件不存在, 打开文件失败
        makeDirectory();
        // 创建了新目录, 直接写文件
        QJsonObject subObj;
        subObj.insert("NodeID", id);
        subObj.insert("Passwd", pwd);
        QString key = t == Type::Client ? "Client" : "Server";
        QJsonObject obj;
        obj.insert(key, subObj);
        QJsonDocument doc(obj);
        array = doc.toBinaryData();
    }
    file.close();
    file.open(QFile::WriteOnly);
    file.write(array);
    file.close();
}

LoginInfo JsonParse::readLoginInfo(JsonParse::Type t)
{
    QFile file(LoginFileName);
    file.open(QFile::ReadOnly);
    QByteArray json = file.readAll();
    QJsonDocument doc = QJsonDocument::fromBinaryData(json);
    QJsonObject obj = doc.object();
    QJsonObject subcli = obj.value("Client").toObject();
    QJsonObject subSer = obj.value("Server").toObject();

    LoginInfo info;
    if(t == Type::Client)
    {
        info.id = subcli.value("NodeID").toString();
        info.pwd = subcli.value("Passwd").toString();
    }
    else
    {
        info.id = subSer.value("NodeID").toString();
        info.pwd = subSer.value("Passwd").toString();
    }
    return info;
}

void JsonParse::delLoginFile()
{
    QDir dir;
    dir.remove(LoginFileName);
}

void JsonParse::writeInterfaceJson(QStringList keys, QStringList values)
{
    QByteArray array = generateSimpleObj(keys, values);
    QFile file(InterfaceFile);
    file.open(QFile::WriteOnly);
    file.write(array);
    file.close();
}



